/* af_unix.c :
 * 
 * AF_UNIX/AF_LOCAL Socket Example:
 */

#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#include <strings.h>
#include <string.h>
#include <sys/un.h>

/* This function reports error and exit to the shell from the program. */
static void
error(const char *msg)
{
	perror(msg);
	exit(1);
}

int main(int argc, char *argv[])
{
	int z;	/* status return code */
	int sock_unix;	/* unix socket fd */
	struct sockaddr_un sock_addr_unix;  /* unix socket address */
	int len_sock_addr_unix;  /* unix socket lentth */
	char const path_unix[] = "/tmp/my_sock";  /* pathname */

	/* Create a AF_UNIX socket */
	sock_unix = socket(AF_UNIX, SOCK_STREAM, 0);
	if(sock_unix == -1)
		error("socket()");

	/* unlink socket file if left linked before this */
	unlink(path_unix);

	/* Form an AF_UNIX socket */
	bzero((char *) &sock_addr_unix, sizeof(sock_addr_unix));
	sock_addr_unix.sun_family = AF_UNIX;
	bcopy(path_unix, sock_addr_unix.sun_path, sizeof(path_unix));

	len_sock_addr_unix = SUN_LEN(&sock_addr_unix);

	/* bind the address to the socket */
	z = bind(sock_unix, (struct sockaddr *) &sock_addr_unix, len_sock_addr_unix);
	if(z < 0)
		error("bind()");

	/* Display all of our bounded sockets */
	system("netstat -pa --unix 2> /dev/null | sed -n '/^Active UNIX/,/^Proto/p;/af_unix/p'");

	/* Close and unlink our socket path */
	close(sock_unix);
	unlink(path_unix);

	return 0;
}
